package com.liaogui.web;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

/**
 * @author liaogui
 * @date 2025/1/7 22:47
 */
@RestController
@RequestMapping("/servlet/")
public class ServletController {
    /**
     * http://localhost:8080/servlet/hello?name=liaogui
     */
    @RequestMapping("/hello")
    public void helloServlet(HttpServletRequest request, HttpServletResponse response, HttpSession session) {
        // 原生对象获取参数
        System.out.println(request.getParameter("name"));
        System.out.println(response.getCharacterEncoding());
        System.out.println(session.getId());
    }

    /**
     * 请求转发
     *
     * @param request  请求
     * @param response 响应
     */
    @RequestMapping("/c2/hello2")
    public void helloServlet2(HttpServletRequest request, HttpServletResponse response) throws Exception {
        request.setAttribute("name", "liaougi");
        request.getRequestDispatcher("/servlet/c2/hello9").forward(request, response);
    }

    /**
     * 重定向
     *
     * @param request  请求
     * @param response 响应
     */
    @RequestMapping("/c2/hello3")
    public void helloServlet3(HttpServletRequest request, HttpServletResponse response) throws Exception {
        request.setAttribute("name", "liaougi");
        response.sendRedirect("/servlet/c2/hello9");
    }

    @RequestMapping("/c2/hello9")
    public void myForward2(HttpServletRequest request){
        System.out.println("hello");
        System.out.println(request.getAttribute("name"));
    }

}
